//小程序服务器地址
// const serverUrl = 'localhost:8080/sw/';

const serverUrl = 'https://s.chengdiankeji.com.cn/sw/';

//授权码key
const TOKEN_KEY = 'Authorized-Token';
const header = {
  Accept: 'application/json',
  'content-type': 'application/json',
  client: 'wechatmini'
};

/**
 * Get请求
 * @param {string} url 请求地址
 * @param {Object} data 参数
 * @param {Function} callback 回调函数
 * @param {string} sources 来自哪个页面的请求
 * @param {boolean} toast 请求接口时显示loading，默认显示
 * @param {boolean} exception 是否处理异常，默认处理
 */
const getRequest = (url, data, callback, sources, toast = true, exception = true) => {
  setAuthToken();
  if (toast) {
    uni.showLoading({
      mask: true,
      title: '加载中...'
    });
  }
  uni.request({
    url: serverUrl + url,
    data: data,
    method: 'GET',
    header: header,
    success: (res) => {
      if (toast) uni.hideLoading();
      return responseHandle(sources, res, callback, exception);
    },
    fail: () => {
      if (toast) uni.hideLoading();
      uni.showToast({ title: '网络错误，请刷新一下吧。^_^!!', icon: 'none' });
      if (typeof callback === 'function') callback(false);
    }
  });
};

// 设置Authorization token
const setAuthToken = () => {
  const token = uni.getStorageSync(TOKEN_KEY) || '';
  console.log('-------->', token);
  header[TOKEN_KEY] = token ? token : '';
};

// Post请求，表单提交
const postRequestForm = (url, data, callback, sources, toast = true) => {
  basePost(sources, url, true, data, callback, toast);
};

// 基础Post请求
const basePost = (sources, url, form, data, callback, toast = true, exception = true) => {
  // const token = uni.getStorageSync(TOKEN_KEY) || '';
  // headers[TOKEN_KEY] = token ? token : '';
  setAuthToken();

  if (toast) {
    uni.showLoading({
      mask: true,
      title: '加载中...'
    });
  }

  if (form) {
    header['Accept'] = '*/*';
    header['content-type'] = 'application/x-www-form-urlencoded';
  }

  uni.request({
    url: serverUrl + url,
    data: data,
    header: header,
    method: 'POST',
    success: (res) => {
      if (toast) uni.hideLoading();
      return responseHandle(sources, res, callback, exception);
    },
    fail: () => {
      if (toast) uni.hideLoading();
      uni.showToast({ title: '网络错误，请刷新一下吧。^_^!!', icon: 'none' });
      if (typeof callback === 'function') callback(false);
    }
  });
};

// 请求成功后的处理函数
const responseHandle = (sources, res, callback, exception) => {
  if (!exception) {
    if (typeof callback === 'function') callback(res.data);
    return;
  }

  switch (parseInt(res.data.code)) {
    case 502:
      uni.setStorageSync(TOKEN_KEY, '');
      if (getCurrentPages().pop().route !== '/pages/login/login') {
        uni.redirectTo({ url: '/pages/login/login?from=' + sources });
      }
      break;
    case 503:
      uni.setStorageSync(TOKEN_KEY, res.data.data || '');
      break;
    case 504:
      uni.showToast({ title: res.data.msg, icon: 'none', duration: 2700 });
      break;
    case 200:
      if (typeof callback === 'function') callback(res.data);
      break;
    case 477:
    case 483:
      uni.navigateTo({ url: `/pages/mistake/mistake?message=${res.data.msg}&text1=${JSON.parse(res.data.data).text1}` });
      break;
    case 506:
      handle506Error(res);
      break;
    default:
      handleDefaultError(res);
      break;
  }
};

// 处理506错误
const handle506Error = (res) => {
  const data = res.data.data;
  const msg = res.data.msg;
  if (typeof data === 'object') {
    if (!msg.text1) {
      uni.redirectTo({ url: `/pages/mistake/mistake?message=${msg}&text1=${data.text1}` });
    }
  } else if (msg) {
    uni.redirectTo({ url: `/pages/mistake/mistake?message=${msg}` });
  }
  if (/^\d+$/.test(data.text1)) {
    uni.redirectTo({ url: `/pages/orderDetail/orderDetail?id=${data.text1}&bomb=true` });
  }
  uni.redirectTo({ url: `/pages/mistake/mistake?message=${msg}` });
};

// 处理默认错误
const handleDefaultError = (res) => {
  const err = res.data.data ? (res.data.code == 470 ? '' : JSON.parse(res.data.data).text1) : '';
  uni.redirectTo({ url: `/pages/error/error?message=${res.data.msg}&err=${err}` });
};

// 导出所有方法和常量
export { serverUrl, TOKEN_KEY, getRequest, postRequestForm, setAuthToken, basePost, responseHandle, handle506Error, handleDefaultError };
